import { message } from 'antd';
import { queryComment, reply, status, deleteReply } from '../services/article';

export default {
  namespace: 'comment',

  state: {
    list:[],
  },

  effects: {
    *fetchMoreComment({payload}, {call, put}){
      const response = yield call(queryComment, payload);
      if(response.status === 'SUCCESS'){
        yield put({
          type:'setMoreList',
          payload: Array.isArray(response.data) ? response.data : [],
        });
      }else{
        message.error(response.failedMsg);
      }
    },
    *fetchComment({payload}, {call, put}){
      const response = yield call(queryComment, payload);
      if(response.status === 'SUCCESS'){
        yield put({
          type:'setList',
          payload: Array.isArray(response.data) ? response.data : [],
        });
      }else{
        message.error(response.failedMsg);
      }
    },
    *reply({payload}, {call, put}){
      const response = yield call(reply, payload);
      if(response.status === 'SUCCESS'){
        yield put({
          type:'resetList',
          payload,
        });
        message.success('回复成功');
      }else{
        message.error(response.failedMsg);
      }
    },
    *status({payload}, {call, put}){
      const response = yield call(status, payload);
      if(response.status === 'SUCCESS'){
        yield put({
          type:'resetList',
          payload,
        });
        message.success('更新成功');
      }else{
        message.error(response.failedMsg);
      }
    },
    *deleteReply({payload}, {call, put}){
      const response = yield call(deleteReply, payload);
      if(response.status === 'SUCCESS'){
        const newpayload = {comment_id: payload.comment_id, reply_content:null};
        console.log(newpayload);
        yield put({
          type:'resetList',
          payload:{...newpayload},
        });
        message.success('更新成功');
      }else{
        message.error(response.failedMsg);
      }
    },
  },

  reducers: {
    setMoreList(state, action){
      return{
        ...state,
        list:state.list.concat(action.payload),
      };
    },
    setList(state, action){
      return{
        ...state,
        list:action.payload,
      };
    },
    resetList(state, action){
      const newlist = state.list;
      for (let i=0; i< newlist.length; i++){
        if(newlist[i].id === Number(action.payload.comment_id)){
          if(action.payload.reply_content !== undefined) {
            newlist[i].reply_content = action.payload.reply_content
          }
          if(action.payload.status !== undefined) {
            newlist[i].status = action.payload.status
          }
        }
      }
      return{
        ...state,
        list:newlist.concat([]),
      };
    },
  },
};
